/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.handler;

import cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.common.RuntimeEnv;
import static cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.common.RuntimeEnv.jsonQueue;
import cn.ac.iie.di.ban.jr.wx.audio.dowloadserver.utils.FileTools;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author Administrator
 */
public class AudioDownloadExe implements Runnable {

    static Logger logger = Logger.getLogger(AudioDownloadExe.class.getName());
    public String respnseDir;
    public JSONObject jsonObj;

    public AudioDownloadExe(String respnseDir, JSONObject jsonObj) {
        this.respnseDir = respnseDir;
        this.jsonObj = jsonObj;
    }

    @Override
    public void run() {
        String url_md5 = null;
        long start = System.currentTimeMillis();
        String message = "";
        try {

            logger.info(start + "====" + jsonObj);
            if (jsonObj != null) {

                String url = jsonObj.getString("url");//真实下载地址
                url_md5 = jsonObj.getString("url_md5");
                InputStream audioStream = null;
                boolean successFlag = false;

                try {
                    int timeOut = Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.timeOut));
                    audioStream = org.apache.http.client.fluent.Request.Get(url).
                            socketTimeout(timeOut)
                            .execute().returnContent().asStream();
                    successFlag = true;
                } catch (Exception ex) {
                    message = ex.getMessage();
                    logger.error(url_md5 + ex.getMessage(), ex);
                } finally {
                    if (!successFlag) {

                        if (message == null) {
                            audioStream = new ByteArrayInputStream("{\"code\":-6,\"errorinfo\":\"音频下载超出预定等待时间，请稍候重试\"}".getBytes("UTF-8"));
                            logger.error(url_md5 + " is " + message + "to download");
                        } else if (message.contains("Forbidden")) {
                            String responseCode = "{\"code\":-7,\"errorinfo\":\"音频文件下载失败，互联网区返回400" + message + "\"}";
                            audioStream = new ByteArrayInputStream(responseCode.getBytes("UTF-8"));
                            logger.error(url_md5 + " is " + message + "to download");
                        } else {
                            audioStream = new ByteArrayInputStream("{\"code\":-6,\"errorinfo\":\"音频下载超出预定等待时间，请稍候重试\"}".getBytes("UTF-8"));
                            logger.error(url_md5 + " is " + message + "to download");
                        }
                    }
                }
                //音频文件成功下载，使用原来的后缀名，否则使用json进行标明
                String fileSuffix = ".json";
                logger.info(url_md5 + " download flag =" + successFlag);
                if (successFlag) {
                    fileSuffix = FileTools.suffix(url);
                }
                if(fileSuffix==null||fileSuffix.equals("null")||fileSuffix.equals("")){
                    fileSuffix=".mp3";
                }
                File file = new File(respnseDir + url_md5 + fileSuffix);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
                int bytesReadIn = 0;
                byte[] bytesContent = new byte[1024 * 2];

                while ((bytesReadIn = audioStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                    bos.write(bytesContent, 0, bytesReadIn);
                }
                bos.flush();
                fileOutputStream.close();
                bos.close();
                logger.info(file.getAbsolutePath() + " download use time (ms): " + (System.currentTimeMillis() - start));
            }
        } catch (IOException ex) {
            logger.error(url_md5 + ex.getMessage());
        } finally {
            logger.info("download exe time (ms): " + (System.currentTimeMillis() - start));

        }

    }

}
